#include "flash_api.h"
#include "nvs_flash.h"

nvs_handle my_handle;
uint8_t flash_set_value_i8(char *table, char *name, uint8_t value)
{
    nvs_open(table, NVS_READWRITE, &my_handle);
    nvs_set_i8(my_handle, name, value);
    return 0;
}

uint8_t flash_get_value_i8(char *table, char *name, int8_t *value)
{
    nvs_open(table, NVS_READONLY, &my_handle);
    nvs_get_i8(my_handle, name, value);
    return 0;
}

uint8_t flash_set_value_i16(char *table, char *name, uint16_t value)
{
    nvs_open(table, NVS_READWRITE, &my_handle);
    nvs_set_i16(my_handle, name, value);
    return 0;
}

uint8_t flash_get_value_i16(char *table, char *name, int16_t *value)
{
    nvs_open(table, NVS_READONLY, &my_handle);
    nvs_get_i16(my_handle, name, value);
    return 0;
}

uint8_t flash_set_value_str(char *table, char *name, char *value)
{
    nvs_open(table, NVS_READWRITE, &my_handle);
    nvs_set_str(my_handle, name, value);

    return 0;
}

uint8_t flash_get_value_str(char *table, char *name, char *value, size_t *len)
{
    esp_err_t err = 0;
    nvs_open(table, NVS_READONLY, &my_handle);
    err = nvs_get_str(my_handle, name, NULL, len);
    char *value_tmp = malloc(*len);
    err = nvs_get_str(my_handle, name, value_tmp, len);
    strcpy(value, value_tmp);
    if (value_tmp)
        free(value_tmp);
    return err;
}

uint8_t flash_commit(void)
{

    nvs_commit(my_handle);
    nvs_close(my_handle);
    return 0;
}

/* 初始化nvs */
void falsh_spiffs_init(void)
{
    //Initialize NVS
    esp_err_t ret = nvs_flash_init();

    if (ret == ESP_ERR_NVS_NO_FREE_PAGES)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
}
